<template>
  <a-drawer
    v-model:open="visible"
    :title="'查看配置'"
    width="1200"
    placement="right"
    @close="handleClose"
  >
    <template v-if="currentChannelTemplate && internalConfigData">
      <a-tabs class="mt-4">
        <a-tab-pane key="base" tab="基础配置">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item
              v-for="item in generateBaseConfigForm()"
              :key="item.key"
              :label="item.schema.label + '：'"
            >
              <template v-if="item.schema.type === 'boolean'">
                <a-tag :color="internalConfigData.baseConfig?.[item.key] ? 'success' : 'error'">
                  {{ internalConfigData.baseConfig?.[item.key] ? '是' : '否' }}
                </a-tag>
              </template>
              <template v-else>
                <a-tooltip v-if="item.schema.description" :title="item.schema.description">
                  <span class="text-gray-600">{{ internalConfigData.baseConfig?.[item.key] || '-' }}</span>
                </a-tooltip>
                <span v-else class="text-gray-600">{{ internalConfigData.baseConfig?.[item.key] || '-' }}</span>
              </template>
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>

        <a-tab-pane key="fee" tab="费率配置">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item
              v-for="item in generateFeeConfigForm()"
              :key="item.key"
              :label="item.schema.label + '：'"
            >
              <template v-if="item.schema.type === 'boolean'">
                <a-tag :color="internalConfigData.feeConfig?.[item.key] ? 'success' : 'error'">
                  {{ internalConfigData.feeConfig?.[item.key] ? '是' : '否' }}
                </a-tag>
              </template>
              <template v-else>
                <a-tooltip v-if="item.schema.description" :title="item.schema.description">
                  <span class="text-gray-600">{{ internalConfigData.feeConfig?.[item.key] || '-' }}</span>
                </a-tooltip>
                <span v-else class="text-gray-600">{{ internalConfigData.feeConfig?.[item.key] || '-' }}</span>
              </template>
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>

        <a-tab-pane key="ext" tab="扩展配置">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item label="扩展配置">
              <pre class="whitespace-pre-wrap">{{ formatJson(internalConfigData?.extraConfig) }}</pre>
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
      </a-tabs>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { getChannelTemplate } from './channel-templates';
import type { ProviderChannelConfig } from './types';

// 内部处理的配置数据，将JSON字符串解析为对象
const internalConfigData = computed(() => {
  if (!props.configData) return null;

  const data = { ...props.configData };

  try {
    // 解析 baseConfig 和 feeConfig 为对象
    data.baseConfig = typeof data.baseConfig === 'string'
      ? JSON.parse(data.baseConfig)
      : data.baseConfig || {};
    data.feeConfig = typeof data.feeConfig === 'string'
      ? JSON.parse(data.feeConfig)
      : data.feeConfig || {};
  } catch (error) {
    console.error('解析配置JSON失败:', error);
    data.baseConfig = {};
    data.feeConfig = {};
  }

  return data;
});

interface Props {
  visible: boolean;
  configData: ProviderChannelConfig | null;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'close'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 根据渠道获取配置模板
const currentChannelTemplate = computed(() => {
  if (!internalConfigData.value?.channelId) return null;

  // 根据渠道ID映射到渠道代码
  const channelMap: Record<number, string> = {
    1: 'WECHAT',
    2: 'ALIPAY',
    3: 'LESHUA',
    4: 'DOUGONG'
  };

  const channelCode = channelMap[internalConfigData.value.channelId];
  return channelCode ? getChannelTemplate(channelCode) : null;
});

// 生成基础配置表单项
const generateBaseConfigForm = () => {
  if (!currentChannelTemplate.value) return [];

  return Object.entries(currentChannelTemplate.value.baseConfigSchema).map(([key, schema]) => ({
    key,
    schema
  }));
};

// 生成费率配置表单项
const generateFeeConfigForm = () => {
  if (!currentChannelTemplate.value) return [];

  return Object.entries(currentChannelTemplate.value.feeConfigSchema).map(([key, schema]) => ({
    key,
    schema
  }));
};

// 格式化JSON
const formatJson = (jsonStr?: string): string => {
  if (!jsonStr) return '{}';
  try {
    const parsed = JSON.parse(jsonStr);
    return JSON.stringify(parsed, null, 2);
  } catch {
    return jsonStr;
  }
};

// 处理关闭
const handleClose = () => {
  emit('update:visible', false);
  emit('close');
};

// 监听visible变化
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});
</script>

<style scoped>
:deep(.ant-tabs-content-holder) {
  padding: 16px 0;
}

:deep(.ant-tabs-tab) {
  padding: 12px 16px;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
}

.text-gray-600 {
  color: #6b7280;
}

.whitespace-pre-wrap {
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
}
</style>